package com.linwen.javase.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName _03LockThread
 * @Description
 * @Author lin
 * @Date 2022/4/19 上午12:13
 * @Version V1.0
 *
 * 使用 ReentrantLock 上锁票数，改写synchronized
 *
 *synchronized默认是可重入锁，ReentrantLock也是可重入锁
 *
 * 可重入锁：也叫递归锁，即同一个锁对象锁着的不同资源，可以一同获取，例如 进了家门之后厨房卧室的门对于你来说都不算门
 *
 *
 */
public class _03LockThread {
    public static void main(String[] args) {
        LTicket lTicket = new LTicket();
        new Thread(()->{
            for (int i = 0; i < 300; i++) {
                lTicket.sale();
            }
        },"AAA").start();
        new Thread(()->{
            for (int i = 0; i < 300; i++) {
                lTicket.sale();
            }
        },"BBB").start();
        new Thread(()->{
            for (int i = 0; i < 300; i++) {
                lTicket.sale();
            }
        },"CCC").start();

    }
}
class LTicket{
    private int tickerNum = 30;
    private ReentrantLock lock = new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if(tickerNum>0){
                System.out.println(Thread.currentThread().getName()+"正在买票"+tickerNum--);
            }
        }finally {
            lock.unlock();
        }
    }
}
